//封装购物车模块

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { addCartService, findCartListService, delCartService , updateCartService } from "@/apis/cart";
import { ElMessage } from "element-plus";

export const useCartStore = defineStore("cart", () => {

    // 1.定义state 
    const cartList = ref([])

    // 2.定义action
    // 查询购物车
    const findCart = async () => {
        const res = await findCartListService()
        cartList.value = res.data
    }
    // 添加购物车
    const addCart = async (goods) => {
        const { id } = goods
        await addCartService(id)
        findCart()
        ElMessage.success("商品已添加到购物车")
    }

    // 修改购物车
    const updateCart = async (data) => {
        await updateCartService(data)
    }
  
    // 删除购物车
    const delCart = async (goodId) => {
        await delCartService(goodId)
        findCart()
    }
    
    // 单选功能
    const singleCheck = (goodId, selected) => {
        const item = cartList.value.find((item) => item.goodId === goodId)
        item.selected = selected
    }

    // 全选功能
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }

    // 已选择商品数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).length)

    // 已选择商品总价
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a,c) => a + c.price,0))
    
    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    // 计算数量
    const allCount = computed(() => cartList.value.length)

    // 计算总价
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.price, 0))

    return {
        cartList,
        addCart,
        updateCart,
        delCart,
        findCart,
        singleCheck,
        allCheck,
        isAll,
        allCount,
        allPrice,
        selectedCount,
        selectedPrice
    }
}, {
    persist: true
})